#!/usr/bin/env python

import os, fire,sys

Base_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(Base_DIR)

# 存在这个文件,覆盖写入
# ALICLOUD_REGION、default_name、default_passwd mysql 是
mysql_base_path = '/home/ubuntu/Desktop/terraform/Terraform/db/rds/mysqlnosmple'
mong_base_path = '/home/ubuntu/Desktop/terraform/Terraform/db/mongodb'
redis_base_path = '/home/ubuntu/Desktop/terraform/Terraform/db/redis'

# dbinstance.py cn-chengdu xhy_test Xhy18473962265 mysql
def mysql(*args):

    # if os.path.exists(os.path.join(path, 'terraform.tfvars')):
    file = os.path.join(mysql_base_path, 'terraform.tfvars')
    with open(file, 'w') as f:
        write_tfvars_mysql(f, *args)
    a = os.popen('cd {0} && terraform init && export TF_LOG=WARN && export TF_LOG_PATH=./terraform.log && terraform apply -auto-approve'.format(mysql_base_path)).readlines()
    print(a)
def write_tfvars_mysql(f, *args):
    f.write("ALICLOUD_REGION = \"{0}\"\n".format(''.join(args[0])))
    f.write("default_name = \"{0}\"\n".format(''.join(args[1])))
    f.write("default_passwd = \"{0}\"\n".format(''.join(args[2])))
    f.close()


def mongo(*args):
    # if os.path.exists(os.path.join(path, 'terraform.tfvars')):
    file = os.path.join(mong_base_path, 'terraform.tfvars')
    with open(file, 'w') as f:
        write_tfvars_mongo(f, *args)
    a = os.popen('cd {0} && terraform init && export TF_LOG=WARN && export TF_LOG_PATH=./terraform.log && terraform apply -auto-approve'.format(mong_base_path)).readlines()
    print(a)
def write_tfvars_mongo(f, *args):
    f.write("ALICLOUD_REGION = \"{0}\"\n".format(''.join(args[0])))
    f.write("default_name = \"{0}\"\n".format(''.join(args[1])))
    f.write("default_passwd = \"{0}\"\n".format(''.join(args[2])))
    f.close()

# 地区，实例名字，密码，创建对象
def redis(*args):
    file = os.path.join(redis_base_path, 'terraform.tfvars')
    with open(file, 'w') as f:
        write_tfvars_redis(f, *args)
    a = os.popen('cd {0} && terraform init && export TF_LOG=WARN && export TF_LOG_PATH=./terraform.log && terraform apply -auto-approve'.format(redis_base_path)).readlines()
    print(a)
def write_tfvars_redis(f, *args):
    f.write("ALICLOUD_REGION = \"{0}\"\n".format(''.join(args[0])))
    f.write("default_name = \"{0}\"\n".format(''.join(args[1])))
    f.write("default_passwd = \"{0}\"\n".format(''.join(args[2])))
    f.close()
def config(*args):
    action = ''.join(args[-1])
    if action == 'mysql':
        fire.Fire(mysql)
    elif action == 'mongodb':
        fire.Fire(mongo)
    elif action == 'redis':
        fire.Fire(redis)



if __name__ == '__main__':
    fire.Fire(config)